package com.xuln.common.category.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import com.xuln.common.category.dao.ICategoryDao;
import com.xuln.common.category.entity.Category;
import com.xuln.framework.dao.BaseDao;
import com.xuln.framework.entity.PrimaryKey;

public class CategoryDaoImpl extends BaseDao<Category, PrimaryKey> implements ICategoryDao {

	public void deleteById(Long categoryId) {
		List<Category> child = getChildCategory(categoryId);
		for (Category category : child) {
			deleteById(category.getPK().getId());
		}
		List<Category> categorys = getChildCategory(categoryId);
		if (categorys != null && categorys.size() > 0) {
			deleteAll(categorys);
		}
	}

	public List<Category> getCategory(Long categoryId) {
		String hql = "from Category c where c.PK.id=?";
		return find(hql, categoryId);
	}

	public List<Category> getChildCategory(Long categoryId) {
		String hql = "from Category c where c.parentId=?";
		return find(hql, categoryId);
	}

	public List<Category> getChildCategory(Long categoryId, String locale) {
		String hql = "from Category c where c.parentId=? and c.PK.locale=?";
		return find(hql, categoryId, locale);

	}

	public List<Category> getAllCategoryByType(String type, String locale) {
		String hql = "from Category c where c.categoryType=? and c.PK.locale=?";
		return find(hql, type, locale);
	}

	public List<Category> getAllChildCategory(Long categoryId, String locale) {
		List<Category> child = getChildCategory(categoryId, locale);
		List<Category> tempChild = new ArrayList<Category>(child);
		for (Category category : tempChild) {
			List<Category> child2 = getAllChildCategory(category.getPK().getId(), locale);
			if (child2 != null && child2.size() > 0) {
				child.addAll(child2);
			}
		}
		return child;
	}

	public List<Category> loadAllByLocale(Locale locale) {
		String hql = "from Category c where c.PK.locale=?";
		return find(hql, locale);
	}

	public List<Category> getAllParent(Long categoryId, String locale) {
		List<Category> parents = new ArrayList<Category>();
		boolean flag = true;
		for (; flag;) {
			Category paraent = getParent(categoryId, locale);
			if (paraent != null) {
				parents.add(paraent);
				if (getParent(paraent.getParentId(), locale) == null) {
					flag = false;
				}
			} else {
				flag = false;
			}

		}
		return parents;
	}

	public Category getParent(Long categoryId, String locale) {
		Category self = get(new PrimaryKey(categoryId, locale));
		if (self == null) {
			return null;
		}
		Category paraent = get(new PrimaryKey(self.getParentId(), locale));
		if (paraent == null) {
			String hql = "from Category c where c.PK.id=?";
			List<Category> paraents = find(hql, self.getParentId());
			if (paraents != null && paraents.size() > 0) {
				paraent = paraents.get(0);
			}
		}
		return paraent;
	}
}
